<template>
  <view>
    <navigationBar ref="navigationBar"/>
    <toast ref="toast"/>
    <loading ref="loading" fullscreen/>

    <view class="post-detail-container" v-if="readyToShow">
      <view class="user-info-container">
        <view class="avatar-container">
          <image :src="postDetail.avatarUrl" mode="aspectFill"/>
        </view>
        <view class="user-container">
          <view class="username">{{ postDetail.username }}</view>
          <view class="post-time">{{ postDetail.postTime }}</view>
        </view>
      </view>
      <view class="post-text-container">
        <u-field
          v-model="postDetail.content"
          disabled
          label-width="0"
          :border-bottom="false"
          :clearable="false"
          maxlength="300"
          :field-style="{
            lineHeight: '50rpx',
            height: '50rpx',
            minHeight: 'calc(50rpx * 2)',
          }"
          type="textarea"/>
      </view>
      <view class="image-container">
        <postImageGroup
          v-if="postDetail.imgList.length !== 0"
          :imageDataList="postDetail.imgList"/>
      </view>
      <view class="tags-container">
        <view
          class="position-tag"
          v-if="postDetail.positionInfo.latitude">
          {{ postDetail.positionInfo.addressName }}
        </view>
      </view>
      <view class="comments-container">
        <view class="divider"></view>
        <view class="title">
          <text class="fa fa-window-minimize fa-rotate-90"></text>
          评论
        </view>
        <view class="comments">
          <view
            class="comment-item"
            v-for="comment in postDetail.commentsList"
            :key="comment.comment.id">
            <view class="user-info-container">
              <view class="avatar-container">
                <image :src="comment.user.avatarUrl == null ? 'https://com-etw.oss-cn-guangzhou.aliyuncs.com/user-avatar/1/3876f256ca244d588605da3903a1628d.png' : comment.user.avatarUrl" mode="aspectFill"/>
              </view>
              <view class="user-container">
                <view class="username">{{ comment.user.name }}</view>
                <view class="post-time">{{ formatTime(comment.comment.createTime) }}</view>
              </view>
              <view class="like-btn">
                <text class="fa fa-heart-o" aria-hidden="true"></text>
              </view>
            </view>
            <view class="comment-content">
              <text>{{comment.comment.content}}</text>
            </view>
          </view>
          <view class="no-comment" v-if="!postDetail.commentsList.length">
            <view>评论区空空如也~</view>
          </view>
        </view>
      </view>
    </view>
    <view
      class="input-area"
      :style="{transform: `translateY(-${keyboardHeight}px)`}">
      <!-- 输入框左侧按钮容器 -->
      <view
        class="more-btn-container"
        :style="{ 
          transform: `translateX(${inputFocusStatus ? '-120': '0'}rpx)`
        }">
        <i
          class="fa fa-picture-o"
          aria-hidden="true"
          :style="{opacity: `${inputFocusStatus ? '0': '1'}`}"
          @click="chooseImage(0)"></i>
        <i
          class="fa fa-camera"
          aria-hidden="true"
          :style="{opacity: `${inputFocusStatus ? '0': '1'}`}"
          @click="chooseImage(1)"></i>
        <i
          class="fa fa-chevron-right"
          aria-hidden="true"
          :style="{opacity: `${inputFocusStatus ? '1': '0'}`}"></i>
      </view>
      <!-- 输入框容器 -->
      <view class="input-container">
        <view
          class="input-inner-container"
          @click="showRawInput"
          :style="{width: `${inputFocusStatus ? 'calc(100vw - 200rpx)' : 'calc(100vw - 220rpx - 80rpx)'}`}">
          <input
            type="text"
            class="raw-input"
            v-model="rawInputValue"
            :focus="inputFocusStatus"
            :adjust-position="false"
            v-if="inputFocusStatus"
            @focus="handleInputFocus"
            @blur="handleInputBlur"
            :confirm-hold="true"
            :confirm-type="`发送`"
            @keyboardheightchange="handleKeyboardHeightChange"
            :auto-blur="true">
          <view
            class="show-input"
            v-if="!inputFocusStatus">
            {{ rawInputValue }}
          </view>
        </view>
        <!-- 输入框右侧发送按钮容器 -->
        <view
          class="send-btn-container"
          @click="sendReply">
          <i class="fa fa-paper-plane" aria-hidden="true"></i>
        </view>
      </view>
    </view>
    <!-- 图片上传组件 -->
    <upload
      class="upload"
      ref="upload"
      :action="action"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :max-size="5242880"
      :max-count="1"
      @on-success="onUploadSuccess" />
  </view>
</template>

<script>
    import navigationBar from '@/components/navigationBar/navigationBar.vue';
    import toast from '@/components/toast/toast.vue';
    import loading from '@/components/loading/loading.vue';
    import postImageGroup from '@/components/postImageGroup/postImageGroup.vue';
    import upload from '@/components/upload/upload.vue';
    import {discussDetail, getUploadSignature, comment} from "@/common/js/api/models";

    export default {
        name: "editPost",
        components: {
            navigationBar, toast, loading, postImageGroup, upload
        },
        data() {
            return {
                postDetail: {
                    postId: NaN,
                    uid: NaN,
                    username: '',
                    postTime: '',
                    avatarUrl: '',
                    title: '我爱你我爱你',
                    content: '',
                    imgList: [],
                    positionInfo: {},
                    commentsList: [
                        {
                            uid: 1,
                            username: 'Cowjiang',
                            commentTime: '11月25日 16:13',
                            avatarUrl: 'https://com-etw.oss-cn-guangzhou.aliyuncs.com/user-avatar/1/3876f256ca244d588605da3903a1628d.png',
                            content: '真好看真好看',
                            likeStatus: false,
                            likeCount: 0,
                            commentCount: 0,
                        },
                        {
                            uid: 2,
                            username: 'Cowjiang',
                            commentTime: '11月25日 16:13',
                            avatarUrl: 'https://com-etw.oss-cn-guangzhou.aliyuncs.com/user-avatar/1/3876f256ca244d588605da3903a1628d.png',
                            content: '真好看真好看',
                            likeStatus: false,
                            likeCount: 0,
                            commentCount: 0,
                        },
                        {
                            uid: 3,
                            username: 'Cowjiang',
                            commentTime: '11月25日 16:13',
                            avatarUrl: 'https://com-etw.oss-cn-guangzhou.aliyuncs.com/user-avatar/1/3876f256ca244d588605da3903a1628d.png',
                            content: '真好看真好看',
                            likeStatus: false,
                            likeCount: 0,
                            commentCount: 0,
                        }
                    ],
                }, //帖子详情数据
                keyboardHeight: 0, //弹起键盘的高度
                rawInputValue: '', //消息输入框的数据
                inputFocusStatus: false, //输入框聚焦状态
                action: '', //图片上传Url
                fileList: [], //发送图片的队列
                readyToShow: false, //是否加载完成
            }
        },
        methods: {
            /**
             * 获取帖子内容
             * @param id {Number} 帖子ID
             */
            getPostDetail(id) {
                discussDetail({
                    urlParam: id,
                    queryData: {
                        page: 1,
                        limit: 10
                    }
                }).then(res => {
                    console.log(res);
                }).catch(res => {
                    console.log(res);
                    if (res.data.code === 200) {
                        const postData = res.data.post;
                        const userData = res.data.user;
                        const comments = res.data.comments;
                        this.postDetail = {
                            postId: postData.id,
                            uid: postData.userId,
                            title: postData.title,
                            username: userData.name,
                            avatarUrl: 'https://com-etw.oss-cn-guangzhou.aliyuncs.com/user-avatar/1/3876f256ca244d588605da3903a1628d.png',
                            imgList: res.data.images,
                            content: postData.content.indexOf('^^^&{') !== -1 ? postData.content.substring(0, postData.content.indexOf('^^^&{')) : postData.content,
                            postTime: this.utils.timestampToTime(postData.createTime),
                            positionInfo: this.getPositionInfo(postData.content),
                            commentsList: comments,
                        }
                        this.readyToShow = true;
                        setTimeout(() => {
                            this.$refs.loading.stopLoading();
                        }, 500);
                    }
                    else {
                        this.$refs.toast.show({
                            text: '获取内容失败',
                            type: 'error'
                        });
                    }
                });
            },
            // 显示消息输入框
            showRawInput() {
                this.inputFocusStatus = true;
            },
            // 监听输入框聚焦事件
            handleInputFocus() {
                // this.inputFocusStatus = true;
            },
            // 监听输入框失焦事件
            handleInputBlur() {
                this.inputFocusStatus = false;
                this.keyboardHeight = 0;
            },
            // 监听键盘弹起高度改变事件
            handleKeyboardHeightChange(e) {
                if (e.detail.height !== 0) {
                    this.keyboardHeight = e.detail.height;
                }
                this.$forceUpdate();
            },
            /**
             * 选择图片
             * @param {Number} mode 选择图片模式，0: 从相册选择图片, 1: 相机拍摄图片
             */
            chooseImage(mode) {
                switch (mode) {
                    case 0:
                        this.$refs.upload.changeSourceType(['album']);
                        this.$refs.upload.selectFile();
                        break;
                    case 1:
                        this.$refs.upload.changeSourceType(['camera']);
                        this.$refs.upload.selectFile();
                        break;
                }
            },
            // 上传图片前的钩子函数
            beforeUpload() {
                let imageTempPath = this.$refs.upload.lists[0].url;
                this.recordsLength += 1;
                return new Promise((resolve, reject) => {
                    let dir = "chat-images";
                    let fileSuffix = imageTempPath.substr(imageTempPath.lastIndexOf("."));
                    this.$refs.toast.show({
                        text: '暂未开放图片评论',
                        type: 'warning'
                    });
                    resolve();
                    getUploadSignature({urlParam: dir})
                        .then((res) => {
                            let signData = res.data;
                            this.action = signData.host;
                            let key = signData.dir + signData.uuid + fileSuffix; //文件路径
                            if (res.success) {
                                this.$refs.upload.formData = {
                                    key: key,
                                    policy: signData.policy,
                                    OSSAccessKeyId: signData.accessId,
                                    success_action_status: "200",
                                    signature: signData.signature,
                                };
                                this.tempFinalSrc = signData.host + "/" + key;
                                resolve();
                            }
                            else {
                                this.recordsLength -= 1;
                                this.$refs.upload.clear();
                                reject();
                            }
                        })
                        .catch((err) => {
                            this.recordsLength -= 1;
                            this.$refs.upload.clear();
                            console.log(err);
                        });
                });
            },
            // 上传图片成功的钩子函数
            onUploadSuccess() {
                // this.$refs.toast.show({
                //     text: '暂未开放图片评论',
                //     type: 'error'
                // });
            },
            // 发送回复/评论
            sendReply() {
                const entityId = this.postDetail.postId;
                const content = this.rawInputValue;
                const entityType = 1;
                const targetId = 0;
                comment({
                    urlParam: this.postDetail.postId,
                    queryData: {
                        entityId: entityId,
                        content: content,
                        entityType: entityType,
                        targetId: targetId,
                    }
                })
                    .then(res  => {
                        console.log(res);
                    })
                    .catch(err => {
                        console.log(err);
                        if (err.data.code === 200) {
                            this.$refs.toast.show({
                                title: '评论成功',
                                type: 'success'
                            });
                            this.getPostDetail(this.postDetail.postId);
                        }
                    });
            },
            getPositionInfo(content) {
                const index = content.indexOf('^^^&');
                if (index !== -1) {
                    let poi = content.substring(index);
                    return {
                        latitude: poi.substring(poi.indexOf('{la='), poi.indexOf('&lo=')).replace('{la=', ''),
                        longitude: poi.substring(poi.indexOf('&lo='), poi.indexOf('&n=')).replace('&lo=', ''),
                        addressName: poi.substring(poi.indexOf('&n='), poi.indexOf('}')).replace('&n=', '')
                    };
                }
                else {
                    return {};
                }
            },
            formatTime(timestamp) {
                return this.utils.timestampToTime(timestamp);
            }
        },
        mounted() {
            this.$refs.loading.startLoading();
            this.$refs.navigationBar.setNavigation({
                titleText: '帖子详情',
                backgroundColor: '#fff',
            });
            const urlParam = this.utils.getCurrentPage().curParam.id || null;
            if (urlParam) {
                const postId = parseInt(urlParam);
                this.getPostDetail(postId);
            }
            else {
                uni.redirectTo({
                    url: '/pages/home/home'
                });
            }
        },
        watch: {}
    }
</script>

<style lang="scss" scoped>
  @import 'postDetail.scss';
</style>